package edu.yale.its.tp.cas.client.filter.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.sun.corba.se.impl.legacy.connection.USLPort;

import edu.yale.its.tp.cas.client.filter.CASFilter;

public class CASFilterExt extends CASFilter{
	
	private List<String> excludedUrlList = new ArrayList<String>();
	private List<String> excludedUrlLists = new ArrayList<String>();
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		Properties p = new Properties();
		try {
			 InputStream is = getClass().getResourceAsStream(
					"/edu/yale/its/tp/cas/client/filter/impl/excludedUrl.properties");
			p.load(is);
			is.close();
		} catch ( Exception e) {
			e.printStackTrace();  
		}
		String[] urlList = p.getProperty("passCasUrl").split(",");
		String[] urlLists = p.getProperty("passCasUrls").split(",");
		for(String s : urlList){
			excludedUrlList.add(s);
		}
		for(String s : urlLists){
			excludedUrlLists.add(s);
		}
		super.init(arg0);
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws ServletException, IOException {
		// TODO Auto-generated method stub
				
		HttpServletRequest request=(HttpServletRequest)arg0;
		String contextPath = request.getContextPath();
		
		String url = request.getRequestURI().substring(contextPath.length());;
		int s=url.indexOf("/",1)>1?url.indexOf("/",1):1;
		String urlString=url.substring(1,s).trim().toLowerCase();
		if (!excludedUrlList.contains(url)&&!excludedUrlLists.contains(urlString)) {
			super.doFilter(arg0, arg1, arg2);
		}else {
			arg2.doFilter(arg0, arg1);
		}
	}	
}
